package net.entelijan.cobean.examples.showcase.combobox;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import net.entelijan.cobean.combobox.DefaultComboBoxInitializer;
import net.entelijan.cobean.core.ISingleSelectionListCobean;
import net.entelijan.cobean.data.literature.ILitService;
import net.entelijan.cobean.data.literature.LitBook;
import net.entelijan.cobean.examples.util.ExamplesUtil;
import net.entelijan.scf.IShowcase;

public class StringWithNullValueComboboxShowcase implements
		IShowcase<ComboboxPanel> {

	private ILitService service = null;

	public StringWithNullValueComboboxShowcase() {
		super();
	}

	@Override
	public void init(final ComboboxPanel panel) {

		DefaultComboBoxInitializer<String> ini = new DefaultComboBoxInitializer<String>();
		ini.setCoComboBox(panel.getComboBox());

		final ISingleSelectionListCobean<String> cobean = ini.initialize();

		// Set some data to the combobox.
		final List<LitBook> books = service.loadAllBooks();
		cobean.setValue(extractTitlesWithNullValue(books));

		panel.getShowSelectedButton().addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(panel, ""
						+ cobean.getSelectedValue());
			}

		});
		panel.getSelect0Button().addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				cobean.setSelectedValue(cobean.getValue().get(0));
			}

		});
		panel.getSelect3Button().addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				cobean.setSelectedValue(cobean.getValue().get(3));
			}

		});
		panel.getUnselectButton().addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				cobean.setSelectedValue(null);
			}

		});
		panel.getSetRestrictedButton().addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				cobean
						.setValue(extractTitlesWithNullValue(ExamplesUtil
								.filterBooksByYear(service.loadAllBooks(),
										1970, 2000)));
			}

		});
		panel.getSetAllButton().addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				cobean.setValue(extractTitlesWithNullValue(service
						.loadAllBooks()));
			}

		});
	}

	private List<String> extractTitlesWithNullValue(List<LitBook> books) {
		ArrayList<String> re = new ArrayList<String>();
		re.add(null);
		for (LitBook book : books) {
			re.add(book.getTitle());
		}
		return re;
	}

	public ILitService getService() {
		return service;
	}

	public void setService(ILitService service) {
		this.service = service;
	}

}
